<template>
    <div class="default-main ba-table-box">
        <el-alert class="ba-table-alert" v-if="baTable.table.remark" :title="baTable.table.remark" type="info"
                  show-icon/>

        <!-- 表格顶部菜单 -->
        <!-- 自定义按钮请使用插槽，甚至公共搜索也可以使用具名插槽渲染，参见文档 -->
        <TableHeader
            :buttons="['refresh','add', 'delete', 'comSearch', 'quickSearch', 'columnDisplay']"
            :quick-search-placeholder="t('Quick search placeholder', { fields: t('scenic.quick Search Fields') })"
        >

            <template #default>
                <el-button class="table-header-operate" type="primary"  @click="addScenic" style="margin-left: 20px">
                    <Icon color="#ffffff" name="el-icon-DocumentAdd"/>
                    <span class="table-header-operate-text">三方添加</span>
                </el-button>


                <el-button class="table-header-operate" type="warning"  @click="batchVipCard" style="margin-left: 20px">
                    <Icon color="#ffffff" name="el-icon-DocumentAdd"/>
                    <span class="table-header-operate-text">批量设置会员</span>
                </el-button>

                <el-button v-blur class="table-header-operate" :disabled="baTable.getSelectionIds().length === 0" type="danger" style="margin-left: 20px" @click="freeze">
                    <Icon color="#ffffff" name="el-icon-CloseBold"/>
                    <span class="table-header-operate-text">批量锁满</span>
                </el-button>

                <el-button v-blur class="table-header-operate" :disabled="baTable.getSelectionIds().length === 0" type="success" style="margin-left: 20px" @click="unhitch">
                    <Icon color="#ffffff" name="el-icon-Check"/>
                    <span class="table-header-operate-text">批量解锁</span>
                </el-button>
            </template>
        </TableHeader>

        <!-- 表格 -->
        <!-- 表格列有多种自定义渲染方式，比如自定义组件、具名插槽等，参见文档 -->
        <!-- 要使用 el-table 组件原有的属性，直接加在 Table 标签上即可 -->
        <Table ref="tableRef">
            <template #limit_nums>
                <el-table-column prop="table_name" align="center" width="130" label="每天限制数量">
                    <template #default="scope">
                        <span v-if="scope.row.limit_nums == 0">无限</span>
                        <span v-else type="success">{{scope.row.limit_nums}}</span>

                    </template>
                </el-table-column>
            </template>

            <template #fifteen>
                <el-table-column prop="table_name" align="center" width="130" label="15天内限制数量">
                    <template #default="scope">
                        <span v-if="scope.row.fifteen == 0">无限</span>
                        <span v-else type="success">{{scope.row.fifteen}}</span>

                    </template>
                </el-table-column>
            </template>



        </Table>

        <Add/>
        <Batch/>
        <BatchLock/>

        <!-- 表单 -->
        <PopupForm/>
        <Lock />
    </div>
</template>

<script setup lang="ts">
import { concat, cloneDeep } from 'lodash-es'
import {onMounted, provide, ref} from 'vue'
import {useI18n} from 'vue-i18n'
import PopupForm from './popupForm.vue'
import {baTableApi} from '/@/api/common'
import {defaultOptButtons} from '/@/components/table'
import TableHeader from '/@/components/table/header/index.vue'
import Table from '/@/components/table/index.vue'
import baTableClass from '/@/utils/baTable'
import Add from './add.vue';
import Batch from './batch.vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import Lock from './lock.vue'
import BatchLock   from "./batch-lock.vue";
import createAxios from "/@/utils/axios";
import {buildJsonToElTreeData} from "/@/utils/common"; // 导入 Element UI 的 Message 组件

defineOptions({
    name: 'scenic',
})

const {t} = useI18n()
const tableRef = ref()
const optButtons: OptButton[] = defaultOptButtons(['weigh-sort','edit', 'delete'])
optButtons.push({
    render: 'tipButton',
    // name 是任意的
    name: 'editStock',
    // title 是语言翻译 key
    title: '锁满',
    text: '',
    type: 'warning',
    icon: 'el-icon-Unlock',
    click: (row: TableRow) => {
        infoButtonClick(row)
    },
})
/**
 * baTable 内包含了表格的所有数据且数据具备响应性，然后通过 provide 注入给了后代组件
 */
const baTable = new baTableClass(
    new baTableApi('/admin/Scenic/'),
    {
        pk: 'id',
        column: [
            {type: 'selection', align: 'center', operator: false},
            {
                label: t('scenic.id'),
                prop: 'id',
                align: 'center',
                width: 70,
                operator: false,
                sortable: 'custom'
            },
            {
                label: t('scenic.string'),
                prop: 'name',
                align: 'center',
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                width: 200,
                sortable: false
            },
            {label: t('scenic.cover'), prop: 'cover', align: 'center', render: 'image', operator: false},
            {
                label: "所属会员卡",
                prop: 'VipCard.name',
                width: 120,
                align: 'center',
                render: 'tags',
                operator: false
            },


            {
                label: "所属会员卡",
                prop: 'vip_card_ids',
                align: 'center',
                operator: 'FIND_IN_SET',
                show: false,
                comSearchRender: 'remoteSelect',
                remote: {pk: 'ba_vip_card.id', field: 'name', remoteUrl: '/admin/vip.Card/index?type=1', multiple: true}
            },

            {
                label: "分类",
                prop: 'cate.name',
                width: 120,
                align: 'center',
                render: 'tags',
                operator: false
            },
            {
                label: "分类",
                prop: 'cate_id',
                align: 'center',
                show: false,
                comSearchRender: 'remoteSelect',
                remote: {pk: 'ba_cate.id', field: 'name', remoteUrl: '/admin/Cate/index'}
            },

            {
                label: "所属省份",
                prop: 'province_name',
                align: 'center',
                width: 140,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                sortable: false
            },


            {
                label: "所属城市",
                prop: 'city_name',
                align: 'center',
                width: 140,
                operatorPlaceholder: t('Fuzzy query'),
                operator: 'LIKE',
                sortable: false
            },

            {
                label: "原价",
                prop: 'normal_price',
                width: 120,
                align: 'center',
                operator: false,
            },

            {
                label: "会员价",
                prop: 'vip_price',
                width: 120,
                align: 'center',
                operator: false,
            },



            {
                label: "每天限制数量",
                prop: 'limit_nums',
                width: 120,
                align: 'center',
                operator: false,
                render: 'slot',
                slotName: 'limit_nums',
            },
            {
                label: "15天内限制数量",
                prop: 'fifteen',
                width: 120,
                align: 'center',
                operator: false,
                render: 'slot',
                slotName: 'fifteen',
            },

            {
                label: t('scenic.address'),
                prop: 'address',
                align: 'center',
                width: 180,
                operatorPlaceholder: t('Fuzzy query'),
                operator: false,
                sortable: false,
                showOverflowTooltip: true
            },

            {
                label: "排序",
                prop: 'weigh',
                width: 120,
                align: 'center',
                operator: false,
            },

            {
                label: t('scenic.status'),
                prop: 'status',
                align: 'center',
                render: 'switch',
                operator: 'eq',
                sortable: false,
                replaceValue: {'0': t('scenic.status 0'), '1': t('scenic.status 1')}
            },

            {
                label: t('锁满'),
                prop: 'is_lock',
                align: 'center',
                render: 'tag',
                operator: 'eq',
                sortable: false,
                custom: { '0': 'success', '1': 'danger' },

                replaceValue: {'0': t('正常'), '1': t('锁满')}
            },
            {
                label: '锁满原因',
                prop: 'lock_reason',
                align: 'center',
                width: 160,
                operator: false,
                operatorPlaceholder: t('Fuzzy query'),
                showOverflowTooltip: true
            },

            {
                label: '备注',
                prop: 'notes',
                align: 'center',
                width: 160,
                operator: false,
                operatorPlaceholder: t('Fuzzy query'),
                showOverflowTooltip: true
            },
            {
                label: t('scenic.create_time'),
                prop: 'create_time',
                align: 'center',
                render: 'datetime',
                operator: false,
                sortable: 'custom',
                width: 160,
                timeFormat: 'yyyy-mm-dd hh:MM:ss'
            },
            {label: t('Operate'), align: 'center', width: 160, render: 'buttons', buttons: optButtons, operator: false},
        ],
        dblClickNotEditColumn: [undefined, 'status'],
        defaultOrder: {prop: 'weigh', order: 'desc'},

    },
    {
        defaultItems: {traffic_bus: '', scenic_des: '', book_notice: '', status: '1'},
    }
)

provide('baTable', baTable)

const infoButtonClick = (row: TableRow) => {
    if (!row) return
    // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
    let rowClone = cloneDeep(row)
    rowClone.data = rowClone.data ? [{ label: '点击展开', children: buildJsonToElTreeData(JSON.parse(rowClone.data)) }] : []
    baTable.form.items = row
    baTable.form.operate = 'Lock'
}
const batchVipCard = () => {
    if (baTable.getSelectionIds().length == 0) {
        ElMessage.error('至少选择一项数据')
        return false;
    }
    baTable.form.operate = 'Batch'
}

// 新增冻结（锁满）方法
const freeze = async () => {
    let SelectionIds = baTable.getSelectionIds()
    if(SelectionIds.length == 0){
        ElMessage.error('请选择锁满项')
        return false;
    }

    try {
        const { value: lockReason } = await ElMessageBox.prompt('请输入锁满原因', '锁满确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            inputPlaceholder: '请输入锁满原因',
            inputValidator: (value) => {
                if (!value) {
                    return '锁满原因不能为空'
                }
                return true
            },
            type: 'warning'
        })

        const res = await toFreeze(lockReason);
        ElMessage.success(res.msg)
        baTable.onTableHeaderAction('refresh', {})
    } catch (e) {
        // 用户取消操作
        if (e !== 'cancel') {
            ElMessage.error('操作失败')
        }
    }
}

// 新增解冻（解锁）方法
const unhitch = async () => {
    let SelectionIds = baTable.getSelectionIds()
    if(SelectionIds.length == 0){
        ElMessage.error('请选择解锁项')
        return false;
    }

    try {
        await ElMessageBox.confirm('确定要解锁所选项吗？', '解锁确认', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        const res = await toUnhitch();
        ElMessage.success(res.msg)
        baTable.onTableHeaderAction('refresh', {})
    } catch (e) {
        // 用户取消操作
    }
}

// API调用函数
const toFreeze = (reason: string) => {
    return createAxios(
        {
            url: '/admin/Scenic/freeze',
            method: 'POST',
            data:{
                ids: baTable.getSelectionIds(),
                reason: reason
            }
        },{
            loading:true
        }
    );
};

const toUnhitch = () => {
    return createAxios(
        {
            url: '/admin/Scenic/unhitch',
            method: 'POST',
            data:{ids: baTable.getSelectionIds()}
        },{
            loading:true
        }
    );
};

const batchLock = () => {
    if (baTable.getSelectionIds().length == 0) {
        ElMessage.error('至少选择一项数据')
        return false;
    }
    baTable.form.operate = 'BatchLock'
}


const addScenic = (row: TableRow) => {
    baTable.table.extend!.showInfo = true
}

onMounted(() => {
    baTable.table.ref = tableRef.value
    baTable.mount()
    baTable.getIndex()?.then(() => {
        baTable.initSort()
        baTable.dragSort()
    })
})
</script>

<style scoped lang="scss"></style>
